package com.ynyr.jar.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginUtil {

    private static final String REMEMBER_ME_COOKIE_NAME = "imageInformation";

	/**  
	* @Name: checkValidateNum
	* @Description: 检测用户输入的验证码和实际的验证码是否一致。
	* @Author: YXC
	* @Version: V1.00
	* @Create Date: 2016-10-04
	* @Parameters: 无。
	* @Return: boolean
	*/
	public static boolean checkValidateNum(HttpServletRequest request, String checkNumberKey, boolean ignoreCase) {
		HttpSession session = request.getSession(false);
		
		if(session == null) {
			return false;
		}
		
		String checkNum = request.getParameter(checkNumberKey);
		
		if(StringUtils.isEmpty(checkNum)) {
			return false;
		}
		
		String realCheckNumber = (String) session.getAttribute(ValidateImageUtil.CHECK_CODE_KEY);
		
		if(StringUtils.isEmpty(realCheckNumber)) {
			return false;
		}

		if(ignoreCase) {
			return checkNum.equalsIgnoreCase(realCheckNumber);
		}
		return checkNum.equals(realCheckNumber);
	}
	
	/**  
	* @Name: rememberElecUser
	* @Description: 记住当前登录用户一周，在一周之内访问此网站的时候将会自动登录。
	* @Author: YXC
	* @Version: V1.00
	* @Create Date: 2016-10-04
	* @Parameters: ...
	* @Return:无
	*/
	public static void rememberElecUser(HttpServletRequest request, HttpServletResponse response, String path, String logonname, String password) {
		String pwd = StringUtil.encipher(password);
		String logonName = StringUtil.encipher(logonname);
		int maxAge = 7 * 24 * 60 * 60 * 1000;
		String deadTime = (System.currentTimeMillis() + maxAge)+ "";
		String value = StringUtil.reverse(logonName + "|" + pwd + "|" + StringUtil.encipher(deadTime));
		value = value.replaceAll("\\s*", "");

		Cookie cookie = new Cookie(REMEMBER_ME_COOKIE_NAME, value);
		cookie.setMaxAge(maxAge);
		cookie.setPath(path);
		// 不允许通过客户端脚本读取 cookie 信息.
		cookie.setHttpOnly(true);
		response.addCookie(cookie);
	}

	/**
	 * @Name: forgetElecUser
	 * @Description: 使当前登陆用户不能再自动登陆。
	 * @Author: YXC
	 * @Version: V1.00
	 * @Create Date: 2018-04-03
	 * @Parameters: ...
	 * @Return:无
	 */
	public static void forgetElecUser(HttpServletResponse response, String path) {
        Cookie cookie = new Cookie(REMEMBER_ME_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        cookie.setPath(path);
        // 不允许通过客户端脚本读取 cookie 信息.
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
	}

	/**  
	* @Name: decipherElecUserCookie
	* @Description: 解密cookie的信息，如果解密成功，则存入一个字符串数组中!
	* 				*第一个代表logonName, 第二个代表logonPwd。
	* 				*当解密失败的时候返回null.
	* @Author: YXC
	* @Version: V1.00
	* @Create Date: 2016-10-04
	* @Parameters: HttpServletRequest request
	* @Return:解密结果。
	*/
	public static String[] decipherElecUserLogonCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();

		if(cookies == null) {
			return null;
		}

		String name = "imageInformation";
		Cookie cookie = null;
		
		//寻找cookie.
		for(int i = 0; i < cookies.length; i++) {
			if(name.equals(cookies[i].getName())) {
				cookie = cookies[i];
				break;
			}
		}
		
		if(cookie == null) {
			return null;
		}
		
		//给出cookie中的数值。
		String value = cookie.getValue().replaceAll("\\s*", "");
		//System.out.println(value);
		
		if(StringUtils.isEmpty(value)) {
			return null;
		}
		
		String[] infoArr = StringUtil.reverse(value).split("\\|");
		
		//判断长度是否合法。
		if(infoArr.length != 3) {
			return null;
		}
		
		//解密三个字符串。
		for(int i = 0; i < 3; i++) {
			String str = StringUtil.decipher(infoArr[i]);
			infoArr[i] = str;
		}
		
		try {
			long deadTime = Long.parseLong(infoArr[2]);
			//当前时间大于有效期限，返回null.
			if(System.currentTimeMillis() > deadTime) {
				return null;
			}
		} catch(Exception e) {
			return null;
		}
		
		//删除条件均满足，则认为此cookie中存储的用户自动登录信息有效，组装logonName, logonPwd数组，返回。
		return new String[]{infoArr[0], infoArr[1]};
	}
}